<template>
  <div class="content-section" :class="{ active: isActive }">
    <div class="fault-monitor-container">
      <div class="page-header">
        <div class="header-content">
          <div class="header-title">
            <div class="title-icon">⚠️</div>
            <div class="title-text">
              <h1>故障监控</h1>
              <p>实时监控集群健康状态与故障信息</p>
            </div>
          </div>
          <div class="header-actions">
            <div class="status-badge">
              <div class="status-dot" :class="{ 'online': !faultStatus.hasFault, 'error': faultStatus.hasFault }"></div>
              <span>{{ faultStatus.hasFault ? '发现故障' : '系统正常' }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="content">
        <div class="glass-card overview-card">
          <div class="card-header">
            <div class="header-left">
              <div class="card-icon">🔍</div>
              <div class="card-title">
                <h3>集群状态概览</h3>
                <span class="card-subtitle">最后更新: {{ formatUpdateTime(faultStatus.lastUpdate) }}</span>
              </div>
            </div>
            <div class="header-right">
              <button class="modern-btn primary" @click="refreshFaultStatus">
                <i class="btn-icon">🔄</i>
                刷新状态
              </button>
            </div>
          </div>
          
          <div class="card-content">
            <div class="status-alert" :class="{ 'error': faultStatus.hasFault, 'success': !faultStatus.hasFault }">
              <div class="alert-icon">
                {{ faultStatus.hasFault ? '❌' : '✅' }}
              </div>
              <div class="alert-content">
                <h4>{{ faultStatus.hasFault ? faultStatus.message : '系统运行正常' }}</h4>
                <p>{{ faultStatus.hasFault ? faultStatus.details : '所有指标均在正常范围内' }}</p>
              </div>
            </div>
          </div>
        </div>
        
        <div class="glass-card node-card">
          <div class="card-header" @click="toggleNodeCard">
            <div class="header-left">
              <div class="card-icon">🖥️</div>
              <div class="card-title">
                <h3>节点监控</h3>
                <span class="card-subtitle">监控集群中所有节点的状态</span>
              </div>
            </div>
            <div class="header-right">
              <span class="expand-icon" :class="{ 'expanded': nodeCardExpanded }">▶</span>
              <button class="modern-btn primary" @click.stop="fetchNodeMetrics">
                <i class="btn-icon">🔄</i>
                刷新节点
              </button>
            </div>
          </div>

          <div v-if="nodeCardExpanded" class="card-content">
             <div class="stats-grid">
              <div class="stat-card">
                <div class="stat-icon">📦</div>
                <div class="stat-content">
                  <div class="stat-number">{{ totalNodes }}</div>
                  <div class="stat-label">总节点数</div>
                </div>
              </div>
              <div class="stat-card success">
                <div class="stat-icon">✅</div>
                <div class="stat-content">
                  <div class="stat-number">{{ readyNodes }}</div>
                  <div class="stat-label">就绪节点</div>
                </div>
              </div>
              <div class="stat-card danger">
                <div class="stat-icon">❌</div>
                <div class="stat-content">
                  <div class="stat-number">{{ abnormalNodes }}</div>
                  <div class="stat-label">异常节点</div>
                </div>
              </div>
            </div>

            <div class="pods-grid" style="margin-top: 24px;">
                <div
                    v-for="node in nodeMetrics"
                    :key="node.name"
                    class="pod-card"
                    :class="getNodeStatusClass(node.status)"
                >
                    <div class="pod-header">
                        <div class="pod-info">
                            <div class="pod-status-indicator" :style="{ backgroundColor: getNodeStatusColor(node.status) }"></div>
                            <div class="pod-details">
                                <h5>{{ node.name }}</h5>
                                <span class="pod-status" :class="getNodeStatusTagType(node.status)">
                                    {{ node.status === 'normal' ? '就绪' : '异常' }}
                                </span>
                            </div>
                        </div>
                    </div>
                     <div v-if="node.message" class="pod-message">
                        {{ node.message }}
                    </div>
                </div>
            </div>
             <p v-if="nodeMetrics.length === 0" style="text-align: center; color: #666; padding: 10px;">暂无节点数据。</p>
          </div>
        </div>

        <div class="glass-card jaeger-card">
          <div class="card-header" @click="toggleJaegerCard">
            <div class="header-left">
              <div class="card-icon">📈</div> 
              <div class="card-title">
                <h3>Jaeger 追踪监控</h3>
                <span class="card-subtitle">实时追踪数据概览</span>
              </div>
            </div>
            <div class="header-right">
              <span class="expand-icon" :class="{ 'expanded': jaegerCardExpanded }">▶</span>
              <button class="modern-btn primary" @click.stop="refreshJaegerMetrics">
                <i class="btn-icon">🔄</i>
                刷新追踪
              </button>
            </div>
          </div>
          <div v-if="jaegerCardExpanded" class="card-content">
            <div class="stats-grid">
              <div class="stat-card">
                <div class="stat-icon">📊</div>
                <div class="stat-content">
                  <div class="stat-number">{{ jaegerMetrics.totalTraces }}</div>
                  <div class="stat-label">总追踪数</div>
                </div>
              </div>
              <div class="stat-card" :class="{ 'danger': jaegerMetrics.errorTraces > 0, 'success': jaegerMetrics.errorTraces === 0 }">
                <div class="stat-icon">{{ jaegerMetrics.errorTraces > 0 ? '🚨' : '✅' }}</div>
                <div class="stat-content">
                  <div class="stat-number">{{ jaegerMetrics.errorTraces }}</div>
                  <div class="stat-label">错误追踪</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon">⏱️</div>
                <div class="stat-content">
                  <div class="stat-number">{{ formatDuration(jaegerMetrics.avgDuration) }}</div>
                  <div class="stat-label">平均耗时</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon">⚡</div>
                <div class="stat-content">
                  <div class="stat-number">{{ jaegerMetrics.servicesCount }}</div>
                  <div class="stat-label">服务数量</div>
                </div>
              </div>
            </div>
            <div class="status-alert success" style="margin-top: 20px;" v-if="jaegerMetrics.totalTraces > 0">
              <div class="alert-icon">
                {{ jaegerMetrics.errorTraces > 0 ? '⚠️' : '✨' }}
              </div>
              <div class="alert-content">
                <h4>{{ jaegerMetrics.errorTraces > 0 ? '部分追踪存在错误或异常' : '追踪系统运行良好' }}</h4>
                <p>最近一次更新时间: {{ formatUpdateTime(jaegerMetrics.lastUpdate) }}</p>
              </div>
            </div>

            <div class="namespace-list" style="margin-top: 20px;">
              <div
                v-for="nsJaeger in jaegerMetrics.namespaces"
                :key="'jaeger-' + nsJaeger.namespace"
                class="namespace-item"
                :class="{ 'expanded': nsJaeger.expanded, 'error': nsJaeger.errorTracesInNamespace > 0, 'healthy': nsJaeger.errorTracesInNamespace === 0 }"
              >
                <div class="namespace-header" @click="toggleNamespace(nsJaeger)">
                  <div class="namespace-info">
                    <div class="namespace-status">
                      <div class="expand-icon" :class="{ 'expanded': nsJaeger.expanded }">▶</div>
                      <div class="status-dot" :class="{ 'error': nsJaeger.errorTracesInNamespace > 0, 'online': nsJaeger.errorTracesInNamespace === 0 }"></div>
                    </div>
                    <div class="namespace-details">
                      <h4>{{ nsJaeger.namespace }}</h4>
                      <p>
                        总追踪: {{ nsJaeger.totalTracesInNamespace }} •
                        错误追踪: <span :class="{'danger-text': nsJaeger.errorTracesInNamespace > 0}">{{ nsJaeger.errorTracesInNamespace }}</span>
                      </p>
                    </div>
                  </div>
                  <div class="namespace-status-badge">
                    <span class="status-text" :class="{ 'error': nsJaeger.errorTracesInNamespace > 0, 'healthy': nsJaeger.errorTracesInNamespace === 0 }">
                      {{ nsJaeger.errorTracesInNamespace > 0 ? '异常' : '正常' }}
                    </span>
                  </div>
                </div>

                <div v-if="nsJaeger.expanded" class="namespace-expanded-content">
                  <div class="services-grid">
                    <div v-for="service in nsJaeger.services" :key="service.serviceName" class="service-card">
                      <h5>{{ service.serviceName }}</h5>
                      <div class="service-metrics">
                        <p>总追踪: {{ service.totalTraces }}</p>
                        <p>错误追踪: <span :class="{'danger-text': service.errorTraces > 0}">{{ service.errorTraces }}</span></p>
                        <p>平均耗时: {{ formatDuration(service.avgDuration) }}</p>
                        <p>P99 耗时: {{ formatDuration(service.p99Duration) }}</p>
                      </div>
                    </div>
                    <p v-if="nsJaeger.services.length === 0" style="text-align: center; color: #666; padding: 10px;">此命名空间下暂无 Jaeger 服务追踪数据。</p>
                  </div>
                </div>
              </div>
              <p v-if="jaegerMetrics.namespaces.length === 0" style="text-align: center; color: #666; padding: 10px;">暂无 Jaeger 命名空间追踪数据。</p>
            </div>
          </div>
        </div>
        
        <div class="glass-card namespace-card">
          <div class="card-header" @click="toggleNamespaceCard">
            <div class="header-left">
              <div class="card-icon">📊</div>
              <div class="card-title">
                <h3>命名空间监控</h3>
                <span class="card-subtitle">自动刷新间隔: {{ Math.round(refreshIntervalMs / 1000) }}秒</span>
              </div>
            </div>
            <div class="header-right">
              <span class="expand-icon" :class="{ 'expanded': namespaceCardExpanded }">▶</span>
              <button class="modern-btn primary" @click.stop="refreshAllData">
                <i class="btn-icon">🔄</i>
                刷新全部
              </button>
            </div>
          </div>
          
          <div v-if="namespaceCardExpanded" class="card-content">
            <div class="stats-grid">
              <div class="stat-card">
                <div class="stat-icon">📦</div>
                <div class="stat-content">
                  <div class="stat-number">{{ namespaceMetrics.length }}</div>
                  <div class="stat-label">总命名空间数</div>
                </div>
              </div>
              <div class="stat-card success">
                <div class="stat-icon">✅</div>
                <div class="stat-content">
                  <div class="stat-number">{{ healthyNamespaces }}</div>
                  <div class="stat-label">正常命名空间</div>
                </div>
              </div>
              <div class="stat-card danger">
                <div class="stat-icon">❌</div>
                <div class="stat-content">
                  <div class="stat-number">{{ faultyNamespaces }}</div>
                  <div class="stat-label">异常命名空间</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon">🚀</div>
                <div class="stat-content">
                  <div class="stat-number">{{ totalPods }}</div>
                  <div class="stat-label">总Pod数</div>
                </div>
              </div>
            </div>

            <div class="namespace-list">
              <div
                v-for="namespace in namespaceMetrics"
                :key="namespace.name"
                class="namespace-item"
                :class="{ 'expanded': namespace.expanded, [namespace.overallStatus]: true }"
              >
                <div class="namespace-header" @click="toggleNamespace(namespace)">
                  <div class="namespace-info">
                    <div class="namespace-status">
                      <div class="expand-icon" :class="{ 'expanded': namespace.expanded }">▶</div>
                      <div class="status-dot" :class="{ 'error': namespace.overallStatus === 'error', 'online': namespace.overallStatus === 'healthy' }"></div>
                    </div>
                    <div class="namespace-details">
                      <h4>{{ namespace.name }}</h4>
                      <p>{{ namespace.podCount }} 个Pod • {{ namespace.runningPods }} 运行中 • {{ namespace.errorPods }} 异常</p>
                    </div>
                  </div>
                  <div class="namespace-status-badge">
                    <span class="status-text" :class="namespace.overallStatus">
                      {{ getNamespaceStatusText(namespace.overallStatus) }}
                    </span>
                  </div>
                </div>

                <div v-if="namespace.expanded" class="namespace-expanded-content">
                  <div class="metrics-grid">
                    <div class="metric-item">
                      <div class="metric-header">
                        <span class="metric-title">Pod状态</span>
                        <span class="metric-badge">{{ namespace.podCount }}</span>
                      </div>
                      <div class="metric-details">
                        <div class="metric-row">
                          <span>运行中:</span>
                          <span class="success">{{ namespace.runningPods }}</span>
                        </div>
                        <div class="metric-row">
                          <span>等待中:</span>
                          <span class="warning">{{ namespace.pendingPods }}</span>
                        </div>
                        <div class="metric-row">
                          <span>异常:</span>
                          <span class="danger">{{ namespace.errorPods }}</span>
                        </div>
                      </div>
                    </div>

                    <div class="metric-item">
                      <div class="metric-header">
                        <span class="metric-title">资源使用</span>
                        <span class="metric-badge" :class="getResourceStatusType(namespace.resourceUsage)">
                          {{ namespace.resourceUsage }}%
                        </span>
                      </div>
                      <div class="metric-details">
                        <div class="metric-row">
                          <span>CPU:</span>
                          <span>{{ namespace.cpuUsage }}%</span>
                        </div>
                        <div class="metric-row">
                          <span>内存:</span>
                          <span>{{ namespace.memoryUsage }}%</span>
                        </div>
                        <div class="metric-row">
                          <span>存储:</span>
                          <span>{{ namespace.storageUsage }}%</span>
                        </div>
                      </div>
                    </div>

                    <div class="metric-item">
                      <div class="metric-header">
                        <span class="metric-title">网络状态</span>
                        <span class="metric-badge" :class="getNetworkStatusType(namespace.networkStatus)">
                          {{ namespace.networkStatus }}
                        </span>
                      </div>
                      <div class="metric-details">
                        <div class="metric-row">
                          <span>服务数:</span>
                          <span>{{ namespace.serviceCount }}</span>
                        </div>
                        <div class="metric-row">
                          <span>入口数:</span>
                          <span>{{ namespace.ingressCount }}</span>
                        </div>
                        <div class="metric-row">
                          <span>连接数:</span>
                          <span>{{ namespace.connectionCount }}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="pods-section">
                    <div class="section-header">
                      <h4>Pod详情</h4>
                      <button class="modern-btn secondary" @click="refreshNamespacePods(namespace.name)">
                        <i class="btn-icon">🔄</i>
                        刷新Pod
                      </button>
                    </div>
                    
                    <div class="pods-grid">
                      <div
                        v-for="pod in namespace.pods"
                        :key="pod.name"
                        class="pod-card"
                        :class="getPodStatusClass(pod.displayStatus)"
                      >
                        <div class="pod-header">
                          <div class="pod-info">
                            <div class="pod-status-indicator" :style="{ backgroundColor: getPodStatusColor(pod.displayStatus) }"></div>
                            <div class="pod-details">
                              <h5>{{ pod.name }}</h5>
                              <span class="pod-status" :class="getPodStatusTagType(pod.displayStatus)">
                                {{ pod.displayStatus }}
                              </span>
                            </div>
                          </div>
                          <div class="pod-actions">
                            <div class="dropdown">
                              <button class="dropdown-trigger modern-btn small">
                                操作 ▼
                              </button>
                              <div class="dropdown-menu">
                                <a @click="handlePodAction({ action: 'logs', pod: pod })">📋 查看日志</a>
                                <a @click="handlePodAction({ action: 'describe', pod: pod })">🔍 查看详情</a>
                                <a v-if="isErrorStatus(pod.displayStatus)" @click="handlePodAction({ action: 'restart', pod: pod })">🔄 重启Pod</a>
                                <a @click="handlePodAction({ action: 'delete', pod: pod })" class="danger">🗑️ 删除Pod</a>
                              </div>
                            </div>
                          </div>
                        </div>
                        
                        <div class="pod-metadata">
                          <div class="metadata-item">
                            <span class="metadata-icon">📦</span>
                            <span>阶段: {{ pod.phase }}</span>
                          </div>
                          <div v-if="pod.ready" class="metadata-item">
                            <span class="metadata-icon">✅</span>
                            <span>就绪: {{ pod.ready }}</span>
                          </div>
                          <div v-if="pod.restartCount > 0" class="metadata-item">
                            <span class="metadata-icon">🔄</span>
                            <span>重启: {{ pod.restartCount }}次</span>
                          </div>
                          <div v-if="pod.age" class="metadata-item">
                            <span class="metadata-icon">⏰</span>
                            <span>运行: {{ pod.age }}</span>
                          </div>
                        </div>
                        
                        <div v-if="pod.message" class="pod-message">
                          {{ pod.message }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog v-model="logDialogVisible" :title="`Pod日志 - ${currentPod.name}`" width="80%" :before-close="handleLogDialogClose">
      <div style="margin-bottom: 10px;">
        <el-select v-if="currentPod.containers && currentPod.containers.length > 1" v-model="selectedContainer" placeholder="选择容器" @change="loadPodLogs" style="width: 200px; margin-right: 10px;">
          <el-option v-for="container in currentPod.containers" :key="container" :label="container" :value="container"></el-option>
        </el-select>
        <el-button @click="loadPodLogs" type="primary" size="small">刷新日志</el-button>
      </div>
      <el-input v-model="podLogs" type="textarea" :rows="20" readonly style="font-family: 'Courier New', monospace; font-size: 12px;"></el-input>
    </el-dialog>

    <el-dialog v-model="detailDialogVisible" :title="`Pod详情 - ${currentPod.name}`" width="80%">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="名称">{{ podDetails.metadata?.name }}</el-descriptions-item>
            <el-descriptions-item label="命名空间">{{ podDetails.metadata?.namespace }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatTime(podDetails.metadata?.creationTimestamp) }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ podDetails.status?.phase }}</el-descriptions-item>
            <el-descriptions-item label="节点">{{ podDetails.spec?.nodeName }}</el-descriptions-item>
            <el-descriptions-item label="重启策略">{{ podDetails.spec?.restartPolicy }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="容器信息" name="containers">
          <el-table :data="podDetails.spec?.containers || []" style="width: 100%">
            <el-table-column prop="name" label="容器名称"></el-table-column>
            <el-table-column prop="image" label="镜像"></el-table-column>
            <el-table-column label="端口">
              <template #default="scope">
                <span v-if="scope.row.ports">
                  {{ scope.row.ports.map(p => `${p.containerPort}/${p.protocol || 'TCP'}`).join(', ') }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="JSON" name="json">
          <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 400px; overflow: auto;">{{ JSON.stringify(podDetails, null, 2) }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "FaultSection",
  props: {
    isActive: {
      type: Boolean,
      default: false,
    },
  },
  setup(props) {
    // 响应式数据
    const faultStatus = ref({
      hasFault: false,
      message: "",
      details: "",
      lastUpdate: null,
    });
    
    // 新增：节点指标数据
    const nodeMetrics = ref([]);
    
    const namespaceMetrics = ref([]);
    
    // Jaeger 指标数据结构更新：包含按命名空间分组的列表
    const jaegerMetrics = ref({
      namespaces: [], // 存储 NamespaceJaegerMetricsDto 列表
      totalTraces: 0,
      errorTraces: 0,
      avgDuration: 0, // 整体平均耗时
      servicesCount: 0, // 整体服务数量
      lastUpdate: null,
    });

    // 控制各模块的展开状态
    const nodeCardExpanded = ref(false);
    const jaegerCardExpanded = ref(false);
    const namespaceCardExpanded = ref(false);

    let refreshInterval = null;
    const refreshIntervalMs = ref(200000);

    // 对话框相关
    const logDialogVisible = ref(false);
    const detailDialogVisible = ref(false);
    const activeTab = ref('basic');
    const podLogs = ref('');
    const podDetails = ref({});
    const currentPod = ref({});
    const selectedContainer = ref('');

    // 计算统计数据
    const healthyNamespaces = computed(() => {
      return namespaceMetrics.value.filter(ns => ns.overallStatus === 'healthy').length;
    });

    const faultyNamespaces = computed(() => {
      return namespaceMetrics.value.filter(ns => ns.overallStatus === 'error').length;
    });

    const totalPods = computed(() => {
      return namespaceMetrics.value.reduce((total, ns) => total + ns.podCount, 0);
    });
    
    // 新增：节点统计数据
    const totalNodes = computed(() => nodeMetrics.value.length);
    const readyNodes = computed(() => nodeMetrics.value.filter(n => n.status === 'normal').length);
    const abnormalNodes = computed(() => nodeMetrics.value.filter(n => n.status === 'abnormal').length);


    // 格式化时间
    const formatUpdateTime = (timestamp) => {
      if (!timestamp) return "未更新";
      const date = new Date(timestamp);
      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false,
      });
    };

    const formatTime = (timestamp) => {
      if (!timestamp) return '--';
      return new Date(timestamp).toLocaleString('zh-CN');
    };

    // 格式化时长 (毫秒转为更易读的单位，平均耗时保留一位小数)
    const formatDuration = (ms) => {
      if (ms === 0) return '0.0ms'; // Ensure 0 is formatted with one decimal
      if (ms < 1000) return `${ms.toFixed(1)}ms`; // 小于1秒时保留一位小数，例如：999.5ms
      const seconds = ms / 1000;
      if (seconds < 60) return `${seconds.toFixed(1)}s`; // 秒数保留一位小数
      const minutes = seconds / 60;
      if (minutes < 60) return `${minutes.toFixed(1)}min`; // 分钟保留一位小数
      const hours = minutes / 60;
      return `${hours.toFixed(1)}h`; // 小时保留一位小数
    };

    // 刷新故障状态
    const refreshFaultStatus = async () => {
      try {
        const response = await axios.get("/api/monitor/fault/status");
        faultStatus.value = response.data;
        if (response.data.refreshInterval) {
          refreshIntervalMs.value = response.data.refreshInterval;
        }
      } catch (error) {
        ElMessage.error("获取故障状态失败：" + error.message);
      }
    };

    // 新增：获取节点指标数据
    const fetchNodeMetrics = async () => {
      try {
        const response = await axios.get("/api/monitor/k8s/nodes/detail");
        nodeMetrics.value = response.data || [];
        ElMessage.success("节点状态刷新成功");
      } catch (error) {
        ElMessage.error("获取节点状态失败：" + error.message);
        nodeMetrics.value = [];
      }
    };

    // 获取命名空间指标数据
    const fetchNamespaceMetrics = async () => {
      try {
        // 获取Pod详情
        const podsResponse = await axios.get("/api/monitor/k8s/pods/detail");
        
        // 获取节点详情 (这里不再需要，因为有独立的节点模块)
        // const nodesResponse = await axios.get("/api/monitor/k8s/nodes/detail");

        // 按命名空间分组数据
        const namespaceMap = {};

        // 处理Pod数据 - 确保使用一致的状态判断逻辑
        podsResponse.data.forEach((pod) => {
          if (!namespaceMap[pod.namespace]) {
            namespaceMap[pod.namespace] = {
              name: pod.namespace,
              pods: [],
              nodes: [],
              podCount: 0,
              runningPods: 0,
              pendingPods: 0,
              errorPods: 0,
              expanded: false,
              overallStatus: 'healthy',
              // 模拟数据，实际应该从API获取
              resourceUsage: Math.floor(Math.random() * 100),
              cpuUsage: Math.floor(Math.random() * 100),
              memoryUsage: Math.floor(Math.random() * 100),
              storageUsage: Math.floor(Math.random() * 100),
              networkStatus: Math.random() > 0.8 ? '异常' : '正常',
              serviceCount: Math.floor(Math.random() * 10) + 1,
              ingressCount: Math.floor(Math.random() * 5),
              connectionCount: Math.floor(Math.random() * 100) + 10,
            };
          }

          namespaceMap[pod.namespace].pods.push(pod);
          namespaceMap[pod.namespace].podCount++;

          // 统计Pod状态 - 使用一致的判断逻辑
          const status = pod.displayStatus || pod.status;
          if (status === "Running" || (status.match(/^\d+\/\d+$/) && 
              status.split("/")[0] === status.split("/")[1])) {
            namespaceMap[pod.namespace].runningPods++;
          } else if (status === "Pending" || status === "ContainerCreating" || 
                     status.startsWith("Init:") || status === "PodInitializing") {
            namespaceMap[pod.namespace].pendingPods++;
          } else if (["Completed", "Succeeded"].includes(status)) {
            namespaceMap[pod.namespace].runningPods++;
          } else {
            namespaceMap[pod.namespace].errorPods++;
            namespaceMap[pod.namespace].overallStatus = 'error';
          }
        });

        namespaceMetrics.value = Object.values(namespaceMap);
      } catch (error) {
        ElMessage.error("获取命名空间指标失败：" + error.message);
      }
    };

    // 新增：获取 Jaeger 指标数据并聚合
    const refreshJaegerMetrics = async () => {
      try {
        const response = await axios.get("/api/monitor/jaeger/metrics");
        const namespaceData = response.data || [];

        let totalTracesAgg = 0;
        let errorTracesAgg = 0;
        let servicesCountAgg = 0;
        let totalDurationSum = 0;
        let totalTracesForAvgDuration = 0; // 用于计算加权平均耗时

        namespaceData.forEach(ns => {
          ns.expanded = ns.expanded || false; // 确保 expanded 属性存在
          totalTracesAgg += ns.totalTracesInNamespace;
          errorTracesAgg += ns.errorTracesInNamespace;
          if (ns.services) {
            servicesCountAgg += ns.services.length;
            ns.services.forEach(service => {
              if (service.totalTraces > 0 && service.avgDuration > 0) {
                totalDurationSum += service.totalTraces * service.avgDuration;
                totalTracesForAvgDuration += service.totalTraces;
              }
            });
          }
        });
        
        let overallAvgDuration = 0;
        if (totalTracesForAvgDuration > 0) {
          overallAvgDuration = totalDurationSum / totalTracesForAvgDuration;
        }

        jaegerMetrics.value = {
          namespaces: namespaceData,
          totalTraces: totalTracesAgg,
          errorTraces: errorTracesAgg,
          avgDuration: overallAvgDuration,
          servicesCount: servicesCountAgg,
          lastUpdate: new Date().toISOString(),
        };
        ElMessage.success("Jaeger 追踪数据刷新成功");
      } catch (error) {
        ElMessage.error("获取 Jaeger 追踪数据失败：" + error.message);
        // 如果失败，可以设置默认值或清空数据
        jaegerMetrics.value = {
          namespaces: [],
          totalTraces: 0,
          errorTraces: 0,
          avgDuration: 0,
          servicesCount: 0,
          lastUpdate: new Date().toISOString(),
        };
      }
    };

    // 刷新指定命名空间的Pod数据
    const refreshNamespacePods = async (namespaceName) => {
      try {
        const response = await axios.get(`/api/k8s/pods/${namespaceName}`);
        if (response.data.success) {
          // 更新特定命名空间的Pod数据
          const namespace = namespaceMetrics.value.find(ns => ns.name === namespaceName);
          if (namespace) {
            // 转换API返回的数据格式，使用与原始数据相同的处理逻辑
            namespace.pods = response.data.pods.map(pod => {
              // 获取容器状态信息
              const containerStatuses = pod.status.containerStatuses || [];
              const initContainerStatuses = pod.status.initContainerStatuses || [];
              
              // 计算displayStatus - 使用与fetchNamespaceMetrics相同的逻辑
              let displayStatus = pod.status.phase;
              let hasError = false;
              
              // 检查容器状态，优先显示异常状态
              for (const containerStatus of containerStatuses) {
                if (containerStatus.state) {
                  if (containerStatus.state.waiting) {
                    const reason = containerStatus.state.waiting.reason;
                    if (['CrashLoopBackOff', 'ImagePullBackOff', 'ErrImagePull', 'InvalidImageName', 'CreateContainerConfigError'].includes(reason)) {
                      displayStatus = reason;
                      hasError = true;
                      break;
                    } else if (['ContainerCreating', 'PodInitializing'].includes(reason)) {
                      if (displayStatus === 'Running') {
                        displayStatus = reason;
                      }
                    }
                  } else if (containerStatus.state.terminated) {
                    const reason = containerStatus.state.terminated.reason;
                    if (['Error', 'OOMKilled', 'Completed'].includes(reason)) {
                      displayStatus = reason;
                      if (reason !== 'Completed') {
                        hasError = true;
                      }
                      break;
                    }
                  }
                }
                
                // 检查重启次数
                if (containerStatus.restartCount > 0 && !hasError) {
                  // 如果有重启但当前运行正常，可能之前有问题
                  if (containerStatus.state && containerStatus.state.running) {
                    // 保持当前状态，但记录重启信息
                  }
                }
              }
              
              // 检查初始化容器状态
              for (const initStatus of initContainerStatuses) {
                if (initStatus.state && initStatus.state.waiting) {
                  const reason = initStatus.state.waiting.reason;
                  if (['CrashLoopBackOff', 'ImagePullBackOff'].includes(reason)) {
                    displayStatus = `Init:${reason}`;
                    hasError = true;
                    break;
                  }
                }
              }
              
              // 如果是Running状态，检查就绪状态
              if (displayStatus === 'Running' && containerStatuses.length > 0) {
                const readyCount = containerStatuses.filter(c => c.ready).length;
                const totalCount = containerStatuses.length;
                if (readyCount < totalCount) {
                  displayStatus = `${readyCount}/${totalCount}`;
                }
              }
              
              // 计算就绪状态
              const readyContainers = containerStatuses.filter(c => c.ready).length;
              const totalContainers = containerStatuses.length;
              const ready = totalContainers > 0 ? `${readyContainers}/${totalContainers}` : '0/0';
              
              // 计算重启次数
              const restartCount = containerStatuses.reduce((sum, c) => sum + (c.restartCount || 0), 0);
              
              // 计算年龄
              const age = calculateAge(pod.metadata.creationTimestamp);
              
              // 获取状态消息
              let message = pod.status.message || '';
              if (!message && containerStatuses.length > 0) {
                for (const cs of containerStatuses) {
                  if (cs.state && cs.state.waiting && cs.state.waiting.message) {
                    message = cs.state.waiting.message;
                    break;
                  } else if (cs.state && cs.state.terminated && cs.state.terminated.message) {
                    message = cs.state.terminated.message;
                    break;
                  }
                }
              }
              
              return {
                name: pod.metadata.name,
                namespace: pod.metadata.namespace,
                displayStatus: displayStatus,
                phase: pod.status.phase,
                ready: ready,
                restartCount: restartCount,
                age: age,
                message: message,
                // 保留原始数据以备后用
                rawPod: pod
              };
            });
            
            // 重新计算统计数据 - 使用与原始逻辑相同的判断方式
            namespace.podCount = namespace.pods.length;
            namespace.runningPods = 0;
            namespace.pendingPods = 0;
            namespace.errorPods = 0;
            
            namespace.pods.forEach(pod => {
              const status = pod.displayStatus;
              
              // 使用与原始代码相同的状态判断逻辑
              if (status === "Running" || (status.match(/^\d+\/\d+$/) && 
                  status.split("/")[0] === status.split("/")[1])) {
                namespace.runningPods++;
              } else if (status === "Pending" || status === "ContainerCreating" || 
                         status.startsWith("Init:") || status === "PodInitializing") {
                namespace.pendingPods++;
              } else if (["Completed", "Succeeded"].includes(status)) {
                // 成功完成的也算作正常
                namespace.runningPods++;
              } else {
                // 其他所有状态都视为异常
                namespace.errorPods++;
                namespace.overallStatus = 'error';
              }
            });
            
            // 如果没有异常Pod，重置整体状态
            if (namespace.errorPods === 0) {
              namespace.overallStatus = 'healthy';
            }
          }
        }
        ElMessage.success('Pod数据刷新成功');
      } catch (error) {
        ElMessage.error(`刷新命名空间 ${namespaceName} 的Pod失败：` + error.message);
      }
    };

    // 计算Pod年龄
    const calculateAge = (creationTimestamp) => {
      const now = new Date();
      const created = new Date(creationTimestamp);
      const diffMs = now - created;
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
      const diffHours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
      
      if (diffDays > 0) return `${diffDays}d${diffHours}h`;
      if (diffHours > 0) return `${diffHours}h${diffMinutes}m`;
      return `${diffMinutes}m`;
    };

    // 刷新全部数据
    const refreshAllData = async () => {
      await Promise.all([
        refreshFaultStatus(),
        fetchNodeMetrics(),
        fetchNamespaceMetrics(),
        refreshJaegerMetrics()
      ]);
    };

    // 切换命名空间展开状态 (同时用于 K8s 命名空间和 Jaeger 命名空间)
    const toggleNamespace = (item) => {
      item.expanded = !item.expanded;
    };

    // 切换 Jaeger 模块展开状态
    const toggleJaegerCard = () => {
      jaegerCardExpanded.value = !jaegerCardExpanded.value;
    };
    
    // 新增：切换 Node 模块展开状态
    const toggleNodeCard = () => {
      nodeCardExpanded.value = !nodeCardExpanded.value;
    };

    // 切换命名空间模块展开状态
    const toggleNamespaceCard = () => {
      namespaceCardExpanded.value = !namespaceCardExpanded.value;
    };

    // 获取命名空间状态类型
    const getNamespaceStatusType = (status) => {
      switch (status) {
        case 'healthy': return 'success';
        case 'warning': return 'warning';
        case 'error': return 'danger';
        default: return 'info';
      }
    };

    // 获取命名空间状态文本
    const getNamespaceStatusText = (status) => {
      switch (status) {
        case 'healthy': return '正常';
        case 'warning': return '警告';
        case 'error': return '异常';
        default: return '未知';
      }
    };

    // 获取资源状态类型
    const getResourceStatusType = (usage) => {
      if (usage >= 90) return 'danger';
      if (usage >= 70) return 'warning';
      return 'success';
    };

    // 获取网络状态类型
    const getNetworkStatusType = (status) => {
      return status === '正常' ? 'success' : 'danger';
    };

    // Node相关方法
    const getNodeStatusColor = (status) => {
        return status === 'normal' ? '#67c23a' : '#f56c6c';
    };
    const getNodeStatusTagType = (status) => {
        return status === 'normal' ? 'success' : 'danger';
    };
    const getNodeStatusClass = (status) => {
        return status === 'normal' ? 'pod-running' : 'pod-error';
    };

    // Pod相关方法
    const getPodStatusColor = (status) => {
      if (!status) return "#909399";
      if (status === "Running" || (status.match(/^\d+\/\d+$/) && 
          status.split("/")[0] === status.split("/")[1])) {
        return "#67c23a";
      }
      if (status.match(/^\d+\/\d+$/)) return "#e6a23c";
      if (["Pending", "ContainerCreating"].includes(status)) return "#409eff";
      if (["Completed", "Succeeded"].includes(status)) return "#67c23a";
      if (["CrashLoopBackOff", "ImagePullBackOff", "Error", "Failed", "OOMKilled"].includes(status)) {
        return "#f56c6c";
      }
      return "#e6a23c";
    };

    const getPodStatusTagType = (status) => {
      if (!status) return "info";
      if (status === "Running" || (status.match(/^\d+\/\d+$/) && 
          status.split("/")[0] === status.split("/")[1])) {
        return "success";
      }
      if (status.match(/^\d+\/\d+$/)) return "warning";
      if (["Pending", "ContainerCreating"].includes(status)) return "primary";
      if (["Completed", "Succeeded"].includes(status)) return "success";
      if (["CrashLoopBackOff", "ImagePullBackOff", "Error", "Failed", "OOMKilled"].includes(status)) {
        return "danger";
      }
      return "info";
    };

    const getPodStatusClass = (status) => {
      if (isErrorStatus(status)) return 'pod-error';
      if (status === "Running") return 'pod-running';
      if (["Pending", "ContainerCreating"].includes(status)) return 'pod-pending';
      return 'pod-normal';
    };

    const isErrorStatus = (status) => {
      return ["CrashLoopBackOff", "ImagePullBackOff", "Error", "Failed", "OOMKilled"].includes(status);
    };

    // Pod操作处理
    const handlePodAction = async (command) => {
      const { action, pod } = command;
      
      switch (action) {
        case 'logs':
          await viewPodLogs(pod.name, pod.namespace);
          break;
        case 'describe':
          await describePod(pod.name, pod.namespace);
          break;
        case 'restart':
          await restartPod(pod.name, pod.namespace);
          break;
        case 'delete':
          await deletePod(pod.name, pod.namespace);
          break;
      }
    };

    // 查看Pod日志
    const viewPodLogs = async (podName, namespace) => {
      try {
        const podResponse = await axios.get(`/api/k8s/pods/${podName}/describe?namespace=${namespace}`);
        const containers = podResponse.data.spec?.containers?.map(c => c.name) || [];
        
        currentPod.value = {
          name: podName,
          namespace: namespace,
          containers: containers
        };
        
        if (containers.length > 0) {
          selectedContainer.value = containers.includes('server') ? 'server' : containers[0];
        }
        
        logDialogVisible.value = true;
        await loadPodLogs();
      } catch (error) {
        ElMessage.error('获取Pod信息失败：' + error.message);
      }
    };

    // 加载Pod日志
    const loadPodLogs = async () => {
      try {
        podLogs.value = '正在加载日志...';
        const url = `/api/k8s/pods/${currentPod.value.name}/logs?namespace=${currentPod.value.namespace}${selectedContainer.value ? `&container=${selectedContainer.value}` : ''}`;
        const response = await axios.get(url);
        podLogs.value = response.data || '暂无日志数据';
      } catch (error) {
        podLogs.value = '加载日志失败：' + error.message;
        ElMessage.error('加载Pod日志失败：' + error.message);
      }
    };

    // 查看Pod详情
    const describePod = async (podName, namespace) => {
      try {
        const response = await axios.get(`/api/k8s/pods/${podName}/describe?namespace=${namespace}`);
        currentPod.value = { name: podName, namespace: namespace };
        podDetails.value = response.data;
        detailDialogVisible.value = true;
      } catch (error) {
        ElMessage.error('获取Pod详情失败：' + error.message);
      }
    };

    // 重启Pod
    const restartPod = async (podName, namespace) => {
      try {
        await ElMessageBox.confirm(`确定要重启 Pod ${podName} 吗？`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const response = await axios.post(`/api/k8s/pods/${podName}/restart?namespace=${namespace}`);
        if (response.data.success) {
          ElMessage.success('Pod重启请求已发送');
          // 刷新对应命名空间的数据
          await refreshNamespacePods(namespace);
        } else {
          ElMessage.error('Pod重启失败：' + response.data.message);
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('重启Pod失败：' + error.message);
        }
      }
    };

    // 删除Pod
    const deletePod = async (podName, namespace) => {
      try {
        await ElMessageBox.confirm(`确定要删除 Pod ${podName} 吗？此操作不可恢复。`, '危险操作', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'error'
        });
        
        const response = await axios.delete(`/api/k8s/pods/${podName}?namespace=${namespace}`);
        if (response.data.success) {
          ElMessage.success('Pod删除成功');
          // 刷新对应命名空间的数据
          await refreshNamespacePods(namespace);
        } else {
          ElMessage.error('Pod删除失败：' + response.data.message);
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除Pod失败：' + error.message);
        }
      }
    };

    // 关闭日志对话框
    const handleLogDialogClose = (done) => {
      podLogs.value = '';
      currentPod.value = {};
      selectedContainer.value = '';
      done();
    };

    // 监听isActive变化，当激活时刷新数据
    watch(() => props.isActive, (newVal) => {
      if (newVal) {
        refreshAllData();
      }
    });

    // 生命周期钩子
    onMounted(() => {
      if (props.isActive) {
        refreshAllData();
      }
      
      // 设置自动刷新
      refreshInterval = setInterval(() => {
        if (props.isActive) {
          refreshAllData();
        }
      }, refreshIntervalMs.value);
    });

    onUnmounted(() => {
      if (refreshInterval) {
        clearInterval(refreshInterval);
      }
    });

    return {
      faultStatus,
      nodeMetrics,
      namespaceMetrics,
      jaegerMetrics,
      refreshIntervalMs,
      nodeCardExpanded,
      jaegerCardExpanded,
      namespaceCardExpanded,
      healthyNamespaces,
      faultyNamespaces,
      totalPods,
      totalNodes,
      readyNodes,
      abnormalNodes,
      logDialogVisible,
      detailDialogVisible,
      activeTab,
      podLogs,
      podDetails,
      currentPod,
      selectedContainer,
      formatUpdateTime,
      formatTime,
      formatDuration,
      refreshFaultStatus,
      fetchNodeMetrics,
      fetchNamespaceMetrics,
      refreshJaegerMetrics,
      refreshNamespacePods,
      refreshAllData,
      toggleNamespace,
      toggleNodeCard,
      toggleJaegerCard,
      toggleNamespaceCard,
      getNamespaceStatusType,
      getNamespaceStatusText,
      getResourceStatusType,
      getNetworkStatusType,
      getNodeStatusColor,
      getNodeStatusTagType,
      getNodeStatusClass,
      getPodStatusColor,
      getPodStatusTagType,
      getPodStatusClass,
      isErrorStatus,
      handlePodAction,
      viewPodLogs,
      loadPodLogs,
      describePod,
      restartPod,
      deletePod,
      handleLogDialogClose
    };
  }
};
</script>


<style scoped>
/* 整体容器 */
.fault-monitor-container {
  height: 100%;
  overflow-y: auto;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
}

/* 页面标题 */
.page-header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding: 24px 30px;
  margin-bottom: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title-icon {
  font-size: 32px;
  animation: pulse 2s infinite;
}

.title-text h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.title-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.header-actions {
  display: flex;
  align-items: center;
}

.status-badge {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.2);
  padding: 8px 16px;
  border-radius: 12px;
  color: white;
  font-size: 14px;
  font-weight: 500;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.status-dot.online {
  background: #52c41a;
}

.status-dot.error {
  background: #ff4d4f;
}

/* 内容区域 */
.content {
  padding: 30px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 玻璃卡片效果 */
.glass-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.glass-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 30px;
  background: rgba(102, 126, 234, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

/* 针对可展开的卡片头部，增加手型光标 */
.node-card .card-header,
.jaeger-card .card-header,
.namespace-card .card-header {
  cursor: pointer;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-icon {
  font-size: 24px;
  padding: 8px;
  background: rgba(102, 126, 234, 0.2);
  border-radius: 12px;
}

.card-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.card-subtitle {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 8px;
}

/* 展开/收起图标 */
.expand-icon {
  font-size: 12px;
  color: #667eea;
  transition: transform 0.3s ease;
  margin-left: 10px; /* 调整图标与文字的间距 */
  transform: rotate(0deg); /* 默认收起状态 */
}

.expand-icon.expanded {
  transform: rotate(90deg); /* 展开状态 */
}

/* 现代按钮样式 */
.modern-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  outline: none;
}

.modern-btn.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  margin-left: 10px; /* 调整按钮与展开图标的间距 */
}

.modern-btn.primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.modern-btn.secondary {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  border: 1px solid rgba(102, 126, 234, 0.2);
}

.modern-btn.secondary:hover {
  background: rgba(102, 126, 234, 0.2);
}

.modern-btn.small {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-icon {
  font-size: 14px;
}

/* 卡片内容 */
.card-content {
  padding: 30px;
}

/* 状态警告 */
.status-alert {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  border-radius: 16px;
  border-left: 4px solid;
}

.status-alert.success {
  background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
  border-left-color: #52c41a;
}

.status-alert.error {
  background: linear-gradient(135deg, #fff2f0 0%, #ffccc7 100%);
  border-left-color: #ff4d4f;
}

.alert-icon {
  font-size: 24px;
}

.alert-content h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
}

.alert-content p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

/* 统计网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #f8f9ff 0%, #e6f0ff 100%);
  border-radius: 16px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  border: 1px solid rgba(102, 126, 234, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
}

.stat-card.success {
  background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
  border-color: rgba(82, 196, 26, 0.2);
}

.stat-card.danger {
  background: linear-gradient(135deg, #fff2f0 0%, #ffccc7 100%);
  border-color: rgba(255, 77, 79, 0.2);
}

.stat-icon {
  font-size: 24px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

/* 命名空间列表 */
.namespace-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.namespace-item {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16px;
  border: 1px solid rgba(102, 126, 234, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.namespace-item:hover {
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
}

.namespace-item.expanded {
  border-color: rgba(102, 126, 234, 0.3);
  box-shadow: 0 8px 30px rgba(102, 126, 234, 0.2);
}

.namespace-item.error {
  border-left: 4px solid #ff4d4f;
}

.namespace-item.healthy {
  border-left: 4px solid #52c41a;
}

/* 命名空间头部 */
.namespace-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  cursor: pointer;
  background: rgba(102, 126, 234, 0.05);
  transition: all 0.3s ease;
}

.namespace-header:hover {
  background: rgba(102, 126, 234, 0.1);
}

.namespace-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.namespace-status {
  display: flex;
  align-items: center;
  gap: 8px;
}


.namespace-details h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.namespace-details p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.namespace-status-badge {
  padding: 6px 12px;
  border-radius: 8px;
  font-size: 12px;
  font-weight: 500;
}

.status-text.healthy {
  color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
}

.status-text.error {
  color: #ff4d4f;
  background: rgba(255, 77, 79, 0.1);
}

/* 展开内容 */
.namespace-expanded-content {
  padding: 0 24px 24px 24px;
  background: rgba(255, 255, 255, 0.5);
}

/* 指标网格 */
.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.metric-item {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  padding: 16px;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.metric-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.metric-badge {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

.metric-badge.success {
  background: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.metric-badge.warning {
  background: rgba(250, 173, 20, 0.1);
  color: #faad14;
}

.metric-badge.danger {
  background: rgba(255, 77, 79, 0.1);
  color: #ff4d4f;
}

.metric-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.metric-row {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
}

.metric-row span:first-child {
  color: #666;
}

.metric-row .success {
  color: #52c41a;
  font-weight: 500;
}

.metric-row .warning {
  color: #faad14;
  font-weight: 500;
}

.metric-row .danger {
  color: #ff4d4f;
  font-weight: 500;
}

/* Pods部分 */
.pods-section {
  margin-top: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(102, 126, 234, 0.1);
}

.section-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* Pod网格 */
.pods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 16px;
}

.pod-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  padding: 16px;
  border: 1px solid rgba(102, 126, 234, 0.1);
  transition: all 0.3s ease;
}

.pod-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.15);
}

.pod-card.pod-error {
  border-left: 4px solid #ff4d4f;
  background: rgba(255, 245, 245, 0.9);
}

.pod-card.pod-running {
  border-left: 4px solid #52c41a;
}

.pod-card.pod-pending {
  border-left: 4px solid #1890ff;
}

.pod-card.pod-normal { /* Fallback for statuses not explicitly styled */
  border-left: 4px solid #ccc;
}


.pod-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.pod-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.pod-status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.pod-details h5 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.pod-status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 500;
}

.pod-status.success {
  background: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.pod-status.warning {
  background: rgba(250, 173, 20, 0.1);
  color: #faad14;
}

.pod-status.danger {
  background: rgba(255, 77, 79, 0.1);
  color: #ff4d4f;
}

.pod-status.primary {
  background: rgba(24, 144, 255, 0.1);
  color: #1890ff;
}

/* 下拉菜单 */
.dropdown {
  position: relative;
}

.dropdown-trigger {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  border: 1px solid rgba(102, 126, 234, 0.2);
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(0, 0, 0, 0.1);
  min-width: 120px;
  z-index: 1000;
  display: none;
}

.dropdown:hover .dropdown-menu {
  display: block;
}

.dropdown-menu a {
  display: block;
  padding: 8px 12px;
  color: #333;
  text-decoration: none;
  font-size: 12px;
  cursor: pointer;
  transition: background 0.2s;
}

.dropdown-menu a:hover {
  background: rgba(102, 126, 234, 0.1);
}

.dropdown-menu a.danger {
  color: #ff4d4f;
}

.dropdown-menu a.danger:hover {
  background: rgba(255, 77, 79, 0.1);
}

/* Pod元数据 */
.pod-metadata {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 8px;
}

.metadata-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.metadata-icon {
  font-size: 11px;
}

.pod-message {
  font-size: 12px;
  color: #999;
  font-style: italic;
  background: rgba(0, 0, 0, 0.05);
  padding: 8px;
  border-radius: 6px;
  margin-top: 8px;
}

/* Jaeger 详细服务卡片 */
.services-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
  margin-top: 15px; /* 与上一个元素的间距 */
}

.service-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  padding: 15px;
  border: 1px solid rgba(102, 126, 234, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.service-card h5 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 15px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px dashed rgba(102, 126, 234, 0.1);
  padding-bottom: 8px;
}

.service-metrics p {
  margin: 6px 0;
  font-size: 13px;
  color: #555;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.service-metrics p span {
  font-weight: 500;
  color: #333;
}

.service-metrics p .danger-text {
  color: #ff4d4f;
  font-weight: 600;
}


/* 动画 */
@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.8;
    transform: scale(1.05);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    padding: 16px 20px;
  }
  
  .content {
    padding: 20px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 12px;
  }
  
  .metrics-grid {
    grid-template-columns: 1fr;
  }
  
  .pods-grid {
    grid-template-columns: 1fr;
  }

  .services-grid {
    grid-template-columns: 1fr;
  }

  /* 调整 header-right 布局，确保按钮不挤压图标 */
  .card-header .header-right {
    display: flex;
    align-items: center;
    gap: 10px; /* 调整间距 */
  }

  .modern-btn.primary {
    margin-left: 0; /* 移除额外的左边距 */
  }
}

@media (max-width: 480px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .title-text h1 {
    font-size: 24px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}
</style>